import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class num40 {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        dfs(candidates,target,-1,path,res);
        return res;
    }

    public void dfs(int[] candidates,int target,int depth,List<Integer> path,List<List<Integer>> res) {
        if(target == 0) {
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i = depth + 1;i < candidates.length;i ++) {
            if(candidates[i] > target) {
                return;
            }
            if(i != depth + 1 && candidates[i] == candidates[i - 1]) {
                continue;
            }
            path.add(candidates[i]);
            dfs(candidates,target - candidates[i],i,path,res);
            path.remove(path.size() - 1);
        }
    }
}
